package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.common.CustomException;
import com.example.reggie.entity.Category;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.Setmeal;
import com.example.reggie.mapper.CategoryMapper;
import com.example.reggie.mapper.DishMapper;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.DishService;
import com.example.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 分类信息表（Category）
 *
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService = new DishServiceImpl();

    @Autowired
    private SetmealService setmealService = new SetmealServiceImpl();

    //在删除之前判断是否有所关联，根据id删除分类
    @Override
    public void remove(Long ids) {

        //查询当前是否关联菜品
        LambdaQueryWrapper<Dish> dqw = new LambdaQueryWrapper<>();
        //根据id添加查询条件
        dqw.eq(Dish::getCategoryId, ids);
        int countd = dishService.count(dqw);
        if (countd > 0) {
            //关联，抛出异常
            throw new CustomException("当前目录下存在其他菜品");
        }

        //查询当前是否关联套餐
        LambdaQueryWrapper<Setmeal> sqw = new LambdaQueryWrapper<>();
        //根据id添加查询条件
        sqw.eq(Setmeal::getCategoryId, ids);
        int counts = setmealService.count(sqw);
        if (counts > 0) {
            //关联，抛出异常
            throw new CustomException("当前目录下存在其他套餐");
        }

        //没有关联：正常删除
        super.removeById(ids);

    }
}

